<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="类别名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryName">
              <a-input :disabled="formDisabled" v-model="model.categoryName" placeholder="请输入类别名称"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="类别编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryCode">
              <a-input :disabled="formDisabled" v-model="model.categoryCode" placeholder="请输入类别编码"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="父节点名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="parentId">
              <a-select
                ref="select"
                v-model="model.parentId"
                :disabled="formDisabled"
                placeholder="请选择父级节点"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in parentList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-has="'erpMaterialCategory:check'">
            <a-form-model-item label="审核岗位（费用报销流程专用）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="checkPosition">
              <j-multi-select-tag
                v-model="model.checkPosition"
                :disabled="formDisabled"
                dictCode="check_position"
                type="select">
              </j-multi-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-has="'erpMaterialCategory:check'">
            <a-form-model-item label="金蝶付款用途（金蝶付款专用）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="kingdeePurposeCode">
              <j-dict-select-tag
                v-model="model.kingdeePurposeCode"
                :disabled="formDisabled"
                dictCode="erp_finance_kingdee_base_payment_purpose,fname,fnumber"
                type="select">
              </j-dict-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'ErpMaterialCategoryForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      var validatorCategoryCode = async (rule,value,callback)=>{
        if(value){
          console.log(value)
          const that = this;
          await getAction(this.url.queryByCategoryCode, { categoryCode: value, parentId: this.model.parentId }).then(res => {
            if (res.success) {
              if(res.result == '0') {
                that.onlyEnterpriseName = false
              } else if(res.result == '1' && that.enterpriseName == value) {
                that.onlyEnterpriseName = false
              } else {
                that.onlyEnterpriseName = true
              }
            } else {
              that.$message.warning(res.message)
            }
          })
          if(that.onlyEnterpriseName) {
            callback('类别编码已存在，请重新输入！')
            return;
          }
          callback()
        }
        callback()
      };
      return {
        model:{
          parentId: null
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          categoryName: [
              { required: true, message: '请输入类别名称!', trigger: 'blur'},
          ],
          categoryCode: [
              { required: true, message: '请输入类别编码!', trigger: 'blur'},
              { validator: validatorCategoryCode, trigger: "blur" },
          ],
          // kingdeePurposeCode: [
          //     { required: true, message: '请选择金蝶付款通途!', trigger: 'blur'},
          // ],
        },
        url: {
          add: "/api/erp/purchase/material/erpMaterialCategory/add",
          edit: "/api/erp/purchase/material/erpMaterialCategory/edit",
          queryById: "/api/erp/purchase/material/erpMaterialCategory/queryById",
          queryAllParent: "/api/erp/purchase/material/erpMaterialCategory/queryAllParent",
          queryByCategoryCode: "/api/erp/purchase/material/erpMaterialCategory/queryByCategoryCode",
        },
        parentList: [],
        enterpriseName: null
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        this.findParent(this.model.id)
        // this.parentList = this.parentList.filter(t => t.id !== this.model.id)
        if (!!this.model.categoryCode) {
          this.enterpriseName = this.model.categoryCode
        } else {
          this.enterpriseName = null
        }
        this.visible = true;
      },
      findParent(id) {
        const that = this
        that.parentList = []
        getAction(this.url.queryAllParent).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              if(id !== res.id) {
                that.parentList.push({ 'id':res.id, 'categoryName':res.categoryName })
              }
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch((error)=>{
              that.$emit('unButtonDisable');
            }).finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }

        })
      },
    }
  }
</script>
